package com.lz.kunkun.messageservice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//全局拦截器
public class MyHandlerInterceptor implements HandlerInterceptor {
	//在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object o) throws Exception {
        System.out.printf("preHandle被调用");
        HttpSession session=req.getSession();
        //res.setCharacterEncoding("UTF=8");
        res.setContentType("text/html;charset=UTF-8");
        //判断session是不是新创建的,以及重复登录问题
       // ISessionManagerService flag = ServicesManager.instance.getISessionManagerService();
        if ((session.isNew()||session.getAttribute("sysUser")==null)&&!req.getRequestURI().contains("loginIn")) {
        	//HttpUtil.reportErrorResponse(res, HttpServletResponse.SC_UNAUTHORIZED, "没有登录");
        	res.sendRedirect("/");
        	return false;
        }
        if(req.getRequestURI().equals("/error")) {
        	res.sendRedirect("/s/error.html");
        	return false;
        }
        return true;    //如果false，停止流程，api被拦截
    }
 
    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse res, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle被调用");
    }
 
    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion被调用");
    }

}
